import { createRouter, createWebHashHistory } from "vue-router"
import { staticRouter, errorRouter } from "@/router/modules/staticRouter"
import { initDynamicRouter } from "@/router/modules/dynamicRouter"
import { useRouterStore } from "@/store/modules/routerControl"
import { useUserStore } from "@/store/modules/user"

const router = createRouter({
  history: createWebHashHistory(),
  routes: [...staticRouter, ...errorRouter],
  strict: false,
  scrollBehavior: () => ({ left: 0, top: 0 })
})

/**
 * @description 路由拦截 beforeEach
 * */
router.beforeEach(async (to, from, next) => {
  // 动态设置标题
  const title = import.meta.env.VITE_GLOB_APP_TITLE
  document.title = to.meta.title ? `${to.meta.title} - ${title}` : title

  const routerStore = useRouterStore()
  const userStore = useUserStore()
  const routers = router.getRoutes()
  // 判断是否登录
  if (!userStore.userInfo.name && to.fullPath !== "/login") {
    return next({ path: "/login", replace: true })
  }
  // 动态添加路由
  if (!routers.some((item) => item.path === "/home") && routerStore.initMenuList.length) {
    await initDynamicRouter()
    return next({ ...to, replace: true })
  }
  next()
})

/**
 * @description 重置路由
 * */
export const resetRouter = () => {
  const routerStore = useRouterStore()
  routerStore.flatMenuList.forEach((route) => {
    const { name } = route
    if (name && router.hasRoute(name)) router.removeRoute(name)
  })
}

/**
 * @description 路由跳转错误
 * */
router.onError((error) => {
  console.error("路由错误", error.message)
})

export default router
